package com.itheima.behavior.server.impl;

import com.heima.model.common.behavior.pojos.ApBehaviorEntry;
import com.itheima.behavior.server.ApBehaviorEntryService;
import org.bouncycastle.util.Integers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApBehaviorEntryServiceImpl implements ApBehaviorEntryService {
    @Autowired
    MongoTemplate mongoTemplate;
    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentId(Integer userId, Integer equipmentId) {
        //同时存在 优先使用userid
        if (userId!=null){
            return getUserEntry(userId);
        }else if (equipmentId!=null){
            return getEquipmentEntry(equipmentId);
        }
        return null;
    }

    @Override
    public ApBehaviorEntry findByUserIdOrEquipmentIdnew(Integer userId, Integer equipmentId) {
        //同时存在 优先使用userid
        if (userId!=null){
            return getUserEntrynew(userId);
        }else if (equipmentId!=null){
            return getEquipmentEntrynew(equipmentId);
        }
        return null;
    }

    private ApBehaviorEntry getEquipmentEntrynew(Integer equipmentId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("refId").is(equipmentId)),ApBehaviorEntry.class);
    }

    private ApBehaviorEntry getUserEntrynew(Integer userId) {
        return mongoTemplate.findOne(Query.query(Criteria.where("refId").is(userId)),ApBehaviorEntry.class);
    }

    private ApBehaviorEntry getUserEntry(Integer userId) {
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        apBehaviorEntry.setCreatedTime(new Date());
        apBehaviorEntry.setType(ApBehaviorEntry.Type.USER.getCode());
        apBehaviorEntry.setRefId(userId);
        return mongoTemplate.save(apBehaviorEntry);
    }
    private ApBehaviorEntry getEquipmentEntry(Integer equipmentId) {
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        apBehaviorEntry.setCreatedTime(new Date());
        apBehaviorEntry.setType(ApBehaviorEntry.Type.EQUIPMENT.getCode());
        apBehaviorEntry.setRefId(equipmentId);
        return mongoTemplate.save(apBehaviorEntry);
    }
}
